package middleware

import (
	"github.com/cy77cc/hioshop/utils"
	"github.com/gin-gonic/gin"
	"net/http"
)

func JwtAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenHeader := c.Request.Header.Get("X-Hioshop-Token")
		result := utils.Result{
			ErrNo:  0,
			ErrMsg: "",
			Data:   nil,
		}

		if tokenHeader == "" {
			if c.FullPath() == "/admin/auth/login" || c.FullPath() == "/api/auth/loginByWeixin" {
				c.Next()
				return
			}
			result.ErrNo = 1
			result.ErrMsg = "请求未携带 token，无法访问"
			c.JSON(http.StatusOK, result)
			c.Abort()
			return
		}

		token, err := utils.ParseToken(tokenHeader)
		if err != nil {
			result.ErrNo = 1
			result.ErrMsg = "签名解析失败"
			c.JSON(http.StatusOK, result)
			c.Abort()
			return
		}

		c.Set("id", token.Id)
		c.Next()
	}
}

// 实现多点登录限制
/*
1. 在redis设置一个login hash
2. key为login field为user id value为token
3. 获取id之后判断当前token是不是原来的token
*/

func CBCAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		tokenH, ok := c.Get("token")
		tokenHeader := tokenH.(string)
		// 从query，header，cookie中寻找token，如果都没找到那就返回
		if !ok {
			tokenHeader = c.Request.Header.Get("Authorization")
			if tokenHeader == "" {
				cookie, _ := c.Request.Cookie("jwt")
				tokenHeader = cookie.String()

			}
		}
		result := utils.Result{
			ErrNo:  0,
			ErrMsg: "",
			Data:   nil,
		}

		if tokenHeader == "" {
			result.ErrNo = 1
			result.ErrMsg = "请求未携带 token，无法访问"
			c.JSON(http.StatusOK, result)
			c.Abort()
			return
		}

		c.Next()
	}
}
